package com.fastjrun.security.session;

import com.fastjrun.apiworld.helper.ResultHelper;
import com.fastjrun.apiworld.vo.ResultModel;
import com.fastjrun.share.demo.security.vo.LoginUserVO;
import com.fastjrun.utils.JacksonUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CustomLogoutHandler implements LogoutSuccessHandler {

    @Autowired
    private SessionRegistry sessionRegistry;


    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        // 退出之后 ，将对应session从缓存中清除 SessionRegistryImpl.principals
        sessionRegistry.removeSessionInformation(request.getSession().getId());
        ResultModel<LoginUserVO> result = ResultHelper.ok();
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(JacksonUtils.toJSon(result));
    }
}
